package com.itheima.ydd.controller;

import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysMenuVo;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.security.x509.EDIPartyName;

import java.util.List;

@RestController
@RequestMapping("sys_menu")
@Slf4j
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 所有菜单---看结果最多三层
     *
     * @return
     */
    @GetMapping("allData")
    public ResultData allData() {
        log.info("请求展示所有菜单allData");
        List<SysMenuVo> sysMenuVoList1 = sysMenuService.allData();
        return ResultData.ok("菜单查询成功", sysMenuVoList1);
    }

    /**
     * 菜单详情
     *
     * @param id
     * @return
     */
    @GetMapping("rowInfo")
    public ResultData rowInfo(@RequestParam Integer id) {
        log.info("菜单详情,请求id=" + id);
        SysMenu byId = sysMenuService.getById(id);
        return ResultData.ok("菜单详情请求成功!", byId);

    }

    /**
     * 菜单修改
     *
     * @param sysMenu
     * @return
     */
    @PostMapping("update")
    public ResultData update(@RequestBody SysMenu sysMenu) {
        boolean res = sysMenuService.updateById(sysMenu);
        String title = sysMenu.getTitle();
        if (res) {
            return ResultData.ok("菜单对象-" + title + "-修改成功", "");
        }

        return ResultData.error("修改失败");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @GetMapping("del")
    public ResultData del(@RequestParam Integer id) {
        log.info("请求删除菜单id=" + id);
        //通过传过来的id当作pid查对象,如果能查到对象说明有子类菜单不能删除
        ResultData resultData = sysMenuService.delById(id);
        return resultData;
    }

    /**
     * 添加
     *
     * @param sysMenu
     * @return
     */
    @PostMapping("add")
    public ResultData add(@RequestBody SysMenu sysMenu) {
        log.info("添加请求"+sysMenu.toString());
        //前台传输数据错误,没有传输is_show字段只能手动添加
        sysMenu.setIsShow(1);//默认显示
        boolean save = sysMenuService.save(sysMenu);
        if (save) {
            return ResultData.ok("添加成功", "");
        }
        return ResultData.error("添加失败");
    }

}
